"""
The address frame contains mechanism for adding/modifying addresses
Written By: Daniel Ortiz
"""
import wx
from database.mapclass import Address, AddressBook

class ResizePlugin:
    def __init__(self, cols):
        self.Bind(wx.EVT_SIZE, self.__OnSize)
        self.cols = cols
        
    def __OnSize(self, event):
        """Resize the list ctrl"""
        size = self.GetSize()
        for col, text in enumerate(self.cols):
            self.SetColumnWidth(col, (size[0] - 15) / len(self.cols))
        event.Skip()

class AddressList(wx.ListCtrl, ResizePlugin):
    """List of addresses"""
    def __init__(self, parent, broker,  width = 125):
        """
        @addreses
        (Columns, data)
        """
        addresses = ["Email", "Name"]
        self.parent = parent
        self.broker = broker
        wx.ListCtrl.__init__(self, parent, style = wx.LC_REPORT)
        ResizePlugin.__init__(self, addresses)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelected)
        count = 0
        for col in addresses:
            self.InsertColumn(count, col, width = width)
            count = count + 1

    def AddAddressList(self, address_list, bookindex):
        self.DeleteAllItems()
        for address in address_list:
            for data in address:
                self.Append([data[0], data[1]])
        self.bookindex = bookindex

    def AddBookView(self, bookview):
        self.bookview = bookview

    def AddAddress(self):
        view_frame = AddressViewFrame(self.parent, self, self.bookview.GetBookNames(), "New Address")
        view_frame.CenterOnParent()
        view_frame.Show()

    def SaveAddress(self, book, address):
        self.broker.SaveAddress(address, book, session = True)
        self.bookview.SaveAddress(book, address)
        if self.bookview.IsBookSelected(book):
            self.Append([address[0], address[1]])

    def ModifyAddress(self, book, oaddress, naddress):
        self.broker.UpdateAddress(book, oaddress, naddress)
        self.bookview.UpdateAddress(book, oaddress, naddress)
        index = self.GetIndexFromData(book, oaddress)
        self.SetStringItem(index, 0, naddress[0])
        self.SetStringItem(index, 1, naddress[1])

    def GetSelectionList(self):
        """Return the selections in a list"""
        index = self.GetFirstSelected()
        retr = []
        while index != -1:
            retr.append(index)
            index = self.GetNextSelected(index)
        return retr
    
    def DeleteAddress(self):
        count = 0
        sel = self.GetSelectionList()
        book_list = self.GetBookList(sel)
        for r, book in zip(sel, book_list):
            address_data = self.GetAddressData(r-count)
            self.DeleteItem(r-count)
            count = count + 1
            self.broker.DeleteAddress(book, address_data)
            self.bookview.DeleteAddress(book, address_data)

    def GetBookList(self, selection):
        ret = []
        for s in selection:
            ret.append(self.GetBookFromIndex(s))
        return ret

    def OnSelected(self, event):
        """Save the current selection"""
        self.selection = event.m_itemIndex

    def OnDoubleClick(self, event):
        """Modify the address"""
        book = self.GetBookFromIndex(self.selection)
        view_frame = AddressViewFrame(self.parent, self, [book], "New Address",
                                      data = self.GetAddressData(self.selection))
        view_frame.CenterOnParent()
        view_frame.Show()

    def GetAddressData(self, index):
        ret = []
        for row in range(0, self.GetColumnCount()):
            item = self.GetItem(index, row)
            ret.append(item.GetText())
        return tuple(ret)

    def GetIndexFromData(self, book, address):
        lower, upper = self.bookindex[book]
        for index in range(lower, upper + 1):
            if self.GetAddressData(index) == address:
                return index
            
    def GetSelectionData(self):
        address = []
        for l in self.GetSelectionList():
            address.append(Address(*self.GetAddressData(l)))
        return address

    def GetBookFromIndex(self, index):
        for book, rang in self.bookindex.iteritems():
            if index >= rang[0] and index <= rang[1]:
                return book
    
class BookList(wx.ListCtrl, ResizePlugin):
    """List of address books"""
    def __init__(self, parent, broker, addressview, width = 125):
        wx.ListCtrl.__init__(self, parent, style = wx.LC_REPORT | wx.LC_EDIT_LABELS)
        ResizePlugin.__init__(self, ["Book"])
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelected)
        self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnFinishEdit)
        self.InsertColumn(0, "Book", width = width)
        self.broker = broker
        self.addressview = addressview
        self.Variables()
        
    def Variables(self):
        self.adding = False
        self.book_list = {}

    def OnSelected(self, event):
        """Switch the current selection"""
        self.SwitchBooks()

    def AddBook(self):
        if not self.adding:
            self.adding = True
            self.Append([""])
            self.Focus(self.GetItemCount() - 1)
            self.EditLabel(self.GetItemCount() - 1)

    def DeleteBook(self):
        count = 0
        for r in self.GetSelectionList():
            book = self.GetItemText(r - count)
            self.DeleteItem(r - count)
            self.broker.DeleteAddressBook(book)
            del self.data[book]
            count = count + 1
        self.SwitchBooks()

    def GetBookNames(self):
        return self.data.keys()
        
    def SwitchBooks(self):
        """Switch between the relevant addressbooks"""
        r = []
        book_index = {}
        count = 0
        for index in self.GetSelectionList():
            text = self.GetItemText(index)
            r.append(self.data[text])
            book_index[text] = (count, len(self.data[text]) + count - 1)
            count += len(self.data[text])
        self.addressview.AddAddressList(r, book_index)

    def AddCurrentData(self, data):
        """Add the current data to the window"""
        self.data = data
        for book in self.data.keys():
            self.Append([book])

    def OnFinishEdit(self, event):
        """Check the user input and save it to the database"""
        if event.IsEditCancelled():
            if self.adding:
                self.DeleteItem(self.GetItemCount() - 1)
        else:
            if self.adding:
                self.broker.SaveAddressBook(event.GetLabel(), session = True)
                self.data[event.GetLabel()] = []
            else:
                index = event.GetIndex()
                previous_book = self.data.keys()[index]
                new_book = event.GetLabel()
                self.broker.UpdateAddressBook(previous_book, new_book)
                self.data[new_book] = self.data[previous_book]
                del self.data[previous_book]
        if self.adding:
            self.adding = False
        event.Skip()

    def SaveAddress(self, book, address):
        self.data[book].append(address)

    def UpdateAddress(self, book, oaddress, naddress):
        """Update the address in the booklist"""
        index = self.data[book].index(oaddress)
        self.data[book][index] = naddress
        

    def GetSelectionList(self):
        """Return the selections in a list"""
        index = self.GetFirstSelected()
        retr = []
        while index != -1:
            retr.append(index)
            index = self.GetNextSelected(index)
        return retr

    def DeleteAddress(self, book, data):
        """Delete the data address"""
        self.data[book].remove(data)

    def IsBookSelected(self, book):
        """Checks to see if the current book is selected"""
        for l in self.GetSelectionList():
            if book == self.GetItemText(l):
                return True
        return False

class EmailList(wx.ListCtrl, ResizePlugin):
    def __init__(self, parent, broker, email):
        self.parent = parent
        self.email = email
        wx.ListCtrl.__init__(self, parent, style = wx.LC_REPORT, size = (-1, 100))
        ResizePlugin.__init__(self, ["Address"])
        self.InsertColumn(0, "Address", width = 125)
        for m in email:
            self.Append([m])

class AddressViewFrame(wx.Frame):
    def __init__(self, parent, view,  blist, state, size = (200, 100),
                 data = None):
        self.blist = blist
        self.state = state
        self.view = view
        self.data = data
        wx.Frame.__init__(self, parent, -1, state, size = size,
                          style =wx.DEFAULT_FRAME_STYLE ^(wx.RESIZE_BORDER |
                                                           wx.MAXIMIZE_BOX))
        self.CreateLayout()

    def CreateLayout(self):
        nameLabel = wx.StaticText(self, -1, "Name:")
        emailLabel = wx.StaticText(self, -1, "Email:")
        bookLabel = wx.StaticText(self, -1, "Book:")
        if self.data:
            self.nameText = wx.TextCtrl(self, -1, self.data[1], size = (200, -1))
            self.emailText = wx.TextCtrl(self, -1, self.data[0], size = (200, -1))
        else:
            self.nameText = wx.TextCtrl(self, -1, "", size = (200, -1))
            self.emailText = wx.TextCtrl(self, -1, "", size = (200, -1))
        cancelButton = wx.Button(self, id = wx.ID_CANCEL)
        okButton = wx.Button(self, id = wx.ID_OK)
        self.bookSelect = wx.ComboBox(self, -1, self.blist[0], choices = self.blist)
        self.Bind(wx.EVT_BUTTON, self.OnOk, okButton)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, cancelButton)
        msizer = wx.GridBagSizer(hgap = 5, vgap = 5)
        msizer.Add(nameLabel, pos = (0, 0))
        msizer.Add(emailLabel, pos = (1, 0))
        msizer.Add(self.nameText, pos = (0, 1), span = (1, 3), flag = wx.EXPAND)
        msizer.Add(self.emailText, pos = (1, 1), span = (1, 3), flag = wx.EXPAND)
        msizer.Add(bookLabel, pos = (2, 0))
        msizer.Add(self.bookSelect, pos = (2, 1))
        msizer.Add(cancelButton, pos = (2, 2))
        msizer.Add(okButton, pos = (2, 3))
        self.SetSizer(msizer)
        self.Fit()
    
    def OnOk(self, event):
        book = self.bookSelect.GetValue()
        address = (self.emailText.GetValue(), self.nameText.GetValue())
        if not self.data:
            self.view.SaveAddress(book, address)
        else:
            self.view.ModifyAddress(book, self.data, address)
        self.Destroy()
    
    def OnCancel(self, event):
        self.Destroy()

class AddressFrame(wx.Frame):
    def __init__(self, parent, broker, size = (700, 400), data = None):
        self.parent = parent
        self.broker = broker
        self.size = size
        wx.Frame.__init__(self, parent, -1, "Address Book", size = size, 
                          style = wx.DEFAULT_FRAME_STYLE ^(wx.RESIZE_BORDER |
                                                           wx.MAXIMIZE_BOX))
        self.CenterOnParent()
        self.CreateLayout()
        if isinstance(data, dict):
            self.address_book.AddCurrentData(data)

    def OnQuit(self, event):
        """Quit the relevant application"""
        d = b.Close(session = True)
        d.addCallback(lambda _: self.FinalizeClose())
        d.addErrback(self.CloseWithError)

    def StoreCurrentData(self, data):
        self.address_book.AddCurrentData(data)

    def CloseWithError(self, d):
        print "Close Error", d
        self.FinalizeClose()

    def FinalizeClose(self):
        self.Destroy()
        reactor.stop()
    
    def CreateLayout(self):
        """Layout of the windows in the frame"""
        lBar, rBar = self.CreateBar()
        self.address_list = AddressList(self, self.broker)
        self.address_book = BookList(self, self.broker, self.address_list)
        self.address_list.AddBookView(self.address_book)
        psizer = wx.BoxSizer(wx.HORIZONTAL)
        rsizer = wx.BoxSizer(wx.VERTICAL)
        lsizer = wx.BoxSizer(wx.VERTICAL)
        rsizer.Add(rBar)
        rsizer.Add(self.address_list, 1,  flag = wx.EXPAND)
        lsizer.Add(lBar)
        lsizer.Add(self.address_book, 1, flag = wx.EXPAND)
        psizer.Add(lsizer, 1, flag = wx.EXPAND)
        psizer.Add(rsizer, 2, flag = wx.EXPAND)
        self.SetSizer(psizer)
        size = psizer.GetMinSize()
        if size[0] < self.size[0]:
            size[0] = self.size[0]
        if size[1] < self.size[1]:
            size[1] = self.size[1]
        self.SetSize(size)

    def CreateBar(self):
        """Create a button bar to control the window"""
        add = wx.Button(self, id = wx.ID_ADD, style = wx.BU_EXACTFIT)
        delete = wx.Button(self, id = wx.ID_DELETE, style = wx.BU_EXACTFIT)
        to = wx.Button(self, -1, "To:", style = wx.BU_EXACTFIT)
        cc = wx.Button(self, -1, "Cc:", style = wx.BU_EXACTFIT)
        bcc = wx.Button(self, -1, "Bcc:", style = wx.BU_EXACTFIT)
        add2 = wx.Button(self, -1, "Add", style = wx.BU_EXACTFIT)
        delete2 = wx.Button(self, -1, "Delete", style = wx.BU_EXACTFIT)
        self.Bind(wx.EVT_BUTTON, self.OnAddAddress, add)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteAddress, delete)
        self.Bind(wx.EVT_BUTTON, self.OnTo, to)
        self.Bind(wx.EVT_BUTTON, self.OnCc, cc)
        self.Bind(wx.EVT_BUTTON, self.OnBcc, bcc)
        self.Bind(wx.EVT_BUTTON, self.OnAddBook, add2)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteBook, delete2)
        rightBar = wx.GridBagSizer(hgap = 1, vgap = 1)
        rightBar.Add(add, pos = (0, 0))
        rightBar.Add(delete, pos = (0, 1))
        rightBar.Add(to, pos = (0, 2))
        rightBar.Add(cc, pos = (0, 3))
        rightBar.Add(bcc, pos = (0, 4))
        rightBar.Add((1, 6), pos = (0, 5))
        rightBar.AddGrowableCol(5)
        leftBar = wx.BoxSizer(wx.HORIZONTAL)
        leftBar.Add(add2)
        leftBar.Add(delete2)
        return leftBar, rightBar

    def OnAddAddress(self, event):
        self.address_list.AddAddress()
    
    def OnDeleteAddress(self, event):
        self.address_list.DeleteAddress()
    
    def OnTo(self, event):
        self.__AddToGui("to")
    
    def OnCc(self, event):
        self.__AddToGui("cc")
    
    def OnBcc(self, event):
        self.__AddToGui("bcc")
        
    def __AddToGui(self, text):
        address = self.address_list.GetSelectionData()
        sum = []
        for a in address:
            if a.fullname:
                sum.append("%s <%s>" % (a.fullname, a.email))
            else:
                sum.append("%s" % (a.email))
        data = " , ".join(sum)
        d = self.parent.database_handler
        d.AddEmailFromAddressBook(text, data)

    def OnAddBook(self, event):
        """Add the relevant book to the the list ctrl"""
        self.address_book.AddBook()
    
    def OnDeleteBook(self, event):
        """Delete the relevant book from the list ctrl"""
        self.address_book.DeleteBook()

if __name__ == '__main__':
    b = Broker(DB_URL)
    app = wx.PySimpleApp()
    frame = AddressFrame(None, b)
    frame.Show()
    d = b.GetData(session = True)
    d.addCallback(frame.StoreCurrentData)
    reactor.registerWxApp(app)
    reactor.run()
#    
#
#
#class ResizePlugin:
#    def __init__(self, cols):
#        self.Bind(wx.EVT_SIZE, self.__OnSize)
#        self.cols = cols
#        
#    def __OnSize(self, event):
#        """Resize the list ctrl"""
#        size = self.GetSize()
#        for col, text in enumerate(self.cols):
#            self.SetColumnWidth(col, (size[0] - 15) / len(self.cols))
#        event.Skip()
#
#class AddressList(wx.ListCtrl, ResizePlugin):
#    """List of addresses"""
#    def __init__(self, parent, addresses, apanel, width = 125):
#        """
#        @addreses
#        (Columns, data)
#        """
#        self.parent = parent
#        self.apanel = apanel
#        wx.ListCtrl.__init__(self, parent, style = wx.LC_REPORT)
#        ResizePlugin.__init__(self, addresses)
#        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelected)
#        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
#        self.Bind(wx.EVT_KILL_FOCUS, self.OnFocus)
#        self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
#        self.Variables()
#        count = 0
#        for col in addresses:
#            self.InsertColumn(count, col, width = width)
#            count = count + 1
#            
#    def SetBookView(self, bookview):
#        self.bookview = bookview
#        
#    def Variables(self):
#        """Class-wide variables"""
#        self.selection = None
#        self.focus = False
#        self.address_list = []
#        self.bookindex = {}
#        
#    def OnSelected(self, event):
#        """Save the selection"""
#        self.selection = event.m_itemIndex
#        if self.address_list:
#            v = self.address_list[self.selection]
#            self.apanel.ShowAddress(v)
#            
#    def OnDoubleClick(self, event):
#        if self.selection:
#            name = ""
#            for bookname, index in self.bookindex.iteritems():
#                if self.selection <= index:
#                    name = bookname
#                    ddata = self.bookview.GetDataFromIndex(bookname, self.selection - index)
#                    break
#            view_frame = AddressViewFrame(self.parent,self,  ddata, [name], "Modify Address")
#            view_frame.CenterOnParent()
#            view_frame.Show()
#        
#    def SwitchAddressBook(self, booklist, bookindex):
#        """Switch between relevant address books"""
#        self.DeleteAllItems()
#        for book in booklist:
#            for data in book:
#                self.Append([data["NAME"], data["EMAIL"]])
#        self.address_list = []
#        self.bookindex = bookindex
#        
#    def EditNextItem(self, add):
#        """Edit the next column label"""
#        item = self.GetItem(self.GetItemCount() - 1, add)
#        self.EditLabel(item.GetId())
#        
#    def AddAddress(self):
#        """Add an address"""
#        view_frame = AddressViewFrame(self.parent, self, {"NAME": "", "EMAIL": ""}, self.bookview.GetBookNames(), "New Address")
#        view_frame.CenterOnParent()
#        view_frame.Show()
#        
#    def NewAddress(self, state):
#        bookname = state.keys()[0]
#        if self.bookindex.has_key(bookname):
#            self.bookview.AddAddressToBook(state[bookname], bookname)
#            self.Append([state[bookname]["NAME"], state[bookname]["EMAIL"]])
#        else:
#            self.bookview.AddAddressToBook(state[bookname], bookname)
#            self.bookview.SwitchToBook(bookname)
#        self.Focus(self.GetItemCount() - 1)
#    
#    def ModifyAddress(self, nstate, ostate):
#        bookname = nstate.keys()[0]
#        index = self.bookview.SwitchAddress(bookname, nstate[bookname], ostate)
#        if index:
#            tindex = self.bookindex[bookname]
#            tindex = self.GetLastIndex(bookname, tindex)
#            self.SetStringItem(index + tindex, 0, nstate[bookname]["NAME"])
#            self.SetStringItem(index + tindex, 1, nstate[bookname]["EMAIL"])
#            self.Focus(index + tindex)
#            
#    def GetLastIndex(self, bookname, tindex):
#        """Get the index of the previous book"""
#        rindex = 0
#        for index in self.bookindex.values():
#            if index > rindex and index < tindex:
#                rindex = index
#        return rindex
#    
#    def GetSelectionList(self):
#        """Return the selections in a list"""
#        index = self.GetFirstSelected()
#        retr = []
#        while index != -1:
#            retr.append(index)
#            index = self.GetNextSelected(index)
#        return retr
#    
#    def GetSelectionData(self):
#        """Return the selection data in a list"""
#        address = []
#        for selection in self.GetSelectionList():
#            for bookname, index in self.bookindex.iteritems():
#                if selection <= index:
#                    address.append(self.bookview.GetDataFromIndex(bookname, selection - index))
#                    break
#        return address
#    
#    def DeleteAddress(self):
#        """Delete an address"""
#        count = 0
#        l = self.GetSelectionList()
#        self.bookview.ListRemoveAddress(self.GetBooknamesFromIndex(l))
#        for r in l:
#            self.DeleteItem(r - count)
#            count = count + 1
#            
#    def GetBooknamesFromIndex(self, sel_list):
#        """Returns the bookname from an index"""
#        book_index = {}
#        for sel in sel_list:
#            for bookname, index in self.bookindex.iteritems():
#                if sel <= index:
#                    if not book_index.has_key(bookname):
#                        book_index[bookname] = []
#                    book_index[bookname].append(sel - index)
#        return book_index
#    
#    def OnFocus(self, event):
#        """Lose the current focus"""
#        self.focus = not self.focus
#        event.Skip()
#        
#class AddressBook(wx.ListCtrl, ResizePlugin):
#    """List of address books"""
#    def __init__(self, parent, book, addressview, width = 125):
#        self.parent = parent
#        self.book = book
#        self.addressview = addressview
#        wx.ListCtrl.__init__(self, parent, style = wx.LC_REPORT | wx.LC_EDIT_LABELS)
#        ResizePlugin.__init__(self, ["Book"])
#        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelected)
#        self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnFinishEdit)
#        self.InsertColumn(0, "Book", width = width)
#        self.Variables()
#        self.addressview.SetBookView(self)
#        for bookname in book.keys():
#            self.Append([bookname.alias])            
#            
#    def Variables(self):
#        self.adding = False
#        
#    def OnSelected(self, event):
#        """Switch the current selection"""
#        self.SwitchBooks()
#        
#    def SwitchBooks(self):
#        r = []
#        book_index = {}
#        count = 0
#        for index in self.GetSelectionList():
#            text = self.GetItemText(index)
#            r.append(self.book[text])
#            book_index[text] = len(self.book[text]) + count
#            count += len(self.book[text])
#        self.addressview.SwitchAddressBook(r, book_index)
#        
#    def OnFinishEdit(self, event):
#        """Check for user input"""
#        if event.IsEditCancelled():
#            if self.adding:
#                self.DeleteItem(self.GetItemCount() - 1)
#        else:
#            print self.book, event.GetLabel()
#            if self.adding:
#                m = ABook(-1, event.GetLabel())
#                self.parent.SendToDatabase("Save", m.oname(), m, callback = self.AddNewBook, get = m)
#            else:
#                index = event.GetIndex()
#                prevm = self.book.keys()[index]
#                newm = ABook(-1, event.GetLabel())
#                self.previous_book = prevm
#                self.parent.SendToDatabase("Modify", prevm.oname(), prevm, newm, callback = self.ModifyBook, get = newm)
#        if self.adding:
#            self.adding = False
#        event.Skip()
#        
#    def AddNewBook(self, obj):
#        """Add a new book to the list of books"""
#        print "Add", obj
#        self.book[obj] = []
#        
#    def ModifyBook(self, obj):
#        """Modify the current book"""
#        print self.book
#        mlist = self.book[self.previous_book]
#        del self.book[self.previous_book]
#        self.book[obj] = mlist
#                
#    def GetBookNames(self):
#        return self.book.keys()
#    
#    def GetDataFromIndex(self, bookname, index):
#        return self.book[bookname][index]
#    
#    def SwitchToBook(self, bookname):
#        """Switch to book removes all currently selected books, selects the book from 
#        the inputted bookname, and switches to the corresponding books data"""
#        for l in self.GetSelectionList():
#            self.Select(l, on = False)
#        self.Select(self.book.keys().index(bookname), on = True)
#        self.SwitchBooks()
#        
#    def SwitchAddress(self, bookname, nstate, ostate):
#        """Switch the address state"""
#        count = 0
#        for m in self.book[bookname]:
#            if m == ostate:
#                m = nstate
#                return count
#            count += 1
#                
#    def AddAddressToBook(self, address, bookname):
#        """Append the new address to the book"""
#        self.book[bookname].append(address)
#        
#    def AddBook(self):    
#        """Add the book to the addressbook"""
#        if not self.adding:
#            self.adding = True
#            self.Append([""])
#            self.Focus(self.GetItemCount() - 1)
#            self.EditLabel(self.GetItemCount() - 1)
#            
#    def SearchBook(self, string):
#        """Search the relevant book for the inputted string"""
#        self.search = True
#        search_result = []
#        for bookname, data in self.book.iteritems():
#            for d in data:
#                for name, record in d.iteritems():
#                    if string in record:
#                        search_result.append(d)
#        
#    
#    def CancelSearch(self, event = False):
#        """Cancel the continuing search"""
#        pass
#        
#    def DeleteBook(self):
#        """Delete the current selection from the adressbook"""
#        count = 0
#        for r in self.GetSelectionList():
#            self.DeleteItem(r - count)
#            count = count + 1
#            
#    def ListRemoveAddress(self, book_index):
#        """Remove the relevant addresses from the book"""
#        for bookname, index_list in book_index.iteritems():
#            for index in index_list:
#                del self.book[bookname][index]
#            
#    def GetSelectionList(self):
#        """Return the selections in a list"""
#        index = self.GetFirstSelected()
#        retr = []
#        while index != -1:
#            retr.append(index)
#            index = self.GetNextSelected(index)
#        return retr
#    
#    
#class EmailList(wx.ListCtrl, ResizePlugin):
#    def __init__(self, parent, email):
#        self.parent = parent
#        self.email = email
#        wx.ListCtrl.__init__(self, parent, style = wx.LC_REPORT, size = (-1, 100))
#        ResizePlugin.__init__(self, ["Address"])
#        self.InsertColumn(0, "Address", width = 125)
#        for m in email:
#            self.Append([m])
#        
#class AddressPanel(wx.Panel):
#    def __init__(self, parent, data):
#        self.parent = parent
#        self.data = data
#        wx.Panel.__init__(self, parent)
#        self.CreateLayout()
#        
#    def CreateLayout(self):
#        """Layout the address panel"""
#        self.first = wx.TextCtrl(self, -1, self.data["FIRST"] or "First")
#        self.last = wx.TextCtrl(self, -1, self.data["LAST"] or "Last")
#        self.email = EmailList(self, self.data["EMAIL"])
#        add_email = wx.Button(self, id = wx.ID_ADD)
#        delete_email = wx.Button(self, id = wx.ID_DELETE)
#        to_email = wx.Button(self, label = "To")
#        cc_email = wx.Button(self, label = "Cc")
#        bcc_email = wx.Button(self, label = "Bcc")
#        from_email = wx.Button(self, label = "From")
#        
#        # Sizers
#        nameSizer = wx.GridBagSizer(0, 0)
#        nameSizer.Add((1, 1), pos = (0, 0), span = (1, 2), flag = wx.EXPAND)
#        nameSizer.Add(self.first, pos = (0, 2), flag = wx.ALIGN_RIGHT)
#        nameSizer.Add(self.last, pos = (0, 3), flag = wx.ALIGN_LEFT)
#        nameSizer.Add((1, 1), pos = (0, 4), span = (1, 2), flag = wx.EXPAND)
#        emailSizer = wx.GridBagSizer(3, 3)
#        emailSizer.Add(nameSizer, pos = (0, 0), span = (1, 6), flag = wx.ALIGN_CENTER)
#        emailSizer.Add(self.email, pos = (1, 0), span = (3, 4), flag = wx.EXPAND)
#        emailSizer.Add(add_email, pos = (1, 4))
#        emailSizer.Add(delete_email, pos = (1, 5))
#        emailSizer.Add(to_email, pos = (2, 4))
#        emailSizer.Add(cc_email, pos = (2, 5))
#        emailSizer.Add(bcc_email, pos = (3, 4))
#        emailSizer.Add(from_email, pos = (3, 5))
#        self.SetSizer(emailSizer)
#        
#    def ShowAddress(self, daddr):
#        """Show the current address of an individual"""
#        self.first.SetValue(daddr["FIRST"])
#        self.last.SetValue(daddr["LAST"])
#        for m in daddr["EMAIL"]:
#            self.email.Append([m])
#
#class AddressViewFrame(wx.Frame):
#    def __init__(self, parent, view, ddata, blist, state, size = (200, 100)):
#        self.parent = parent
#        self.ddata = ddata
#        self.blist = blist
#        self.state = state
#        self.view = view
#        wx.Frame.__init__(self, parent, -1, state, size = size,
#                          style =wx.DEFAULT_FRAME_STYLE ^(wx.RESIZE_BORDER |
#                                                           wx.MAXIMIZE_BOX))
#        self.Variables()
#        self.CreateLayout()
#        
#    def Variables(self):
#        self.new_state = "New Address"
#        self.mod_state = "Modify Address"
#    
#    def CreateLayout(self):
#        nameLabel = wx.StaticText(self, -1, "Name:")
#        emailLabel = wx.StaticText(self, -1, "Email:")
#        bookLabel = wx.StaticText(self, -1, "Book:")
#        self.nameText = wx.TextCtrl(self, -1, self.ddata["NAME"] or "", size = (200, -1))
#        self.emailText = wx.TextCtrl(self, -1, self.ddata["EMAIL"] or "", size = (200, -1))
#        cancelButton = wx.Button(self, id = wx.ID_CANCEL)
#        okButton = wx.Button(self, id = wx.ID_OK)
#        self.bookSelect = wx.ComboBox(self, -1, self.blist[0], choices = self.blist)
#        self.Bind(wx.EVT_BUTTON, self.OnOk, okButton)
#        self.Bind(wx.EVT_BUTTON, self.OnCancel, cancelButton)
#        msizer = wx.GridBagSizer(hgap = 5, vgap = 5)
#        msizer.Add(nameLabel, pos = (0, 0))
#        msizer.Add(emailLabel, pos = (1, 0))
#        msizer.Add(self.nameText, pos = (0, 1), span = (1, 3), flag = wx.EXPAND)
#        msizer.Add(self.emailText, pos = (1, 1), span = (1, 3), flag = wx.EXPAND)
#        msizer.Add(bookLabel, pos = (2, 0))
#        msizer.Add(self.bookSelect, pos = (2, 1))
#        msizer.Add(cancelButton, pos = (2, 2))
#        msizer.Add(okButton, pos = (2, 3))
#        self.SetSizer(msizer)
#        self.Fit()
#    
#    def OnOk(self, event):
#        state = {}
#        book = self.bookSelect.GetValue()
#        state[book] = {} 
#        state[book]["NAME"] = self.nameText.GetValue()
#        state[book]["EMAIL"] = self.emailText.GetValue()
#        if self.state == self.new_state:
#            self.view.NewAddress(state)
#        elif self.state == self.mod_state:
#            self.view.ModifyAddress(state, self.ddata)
#        self.Destroy()
#    
#    def OnCancel(self, event):
#        self.Destroy()
#
#class AddressFrame(wx.Frame):
#    def __init__(self, parent, dbhandler, ddata = None, size = (700, 400)):
#        self.parent = parent
#        self.dbhandler = dbhandler
#        self.ddata = self.dbhandler.GetAddressBook()
#        self.size = size
#        wx.Frame.__init__(self, parent, -1, "Address Book", size = size, 
#                          style = wx.DEFAULT_FRAME_STYLE ^(wx.RESIZE_BORDER |
#                                                           wx.MAXIMIZE_BOX))
#        self.CenterOnParent()
#        self.CreateLayout()
#    
#    def CreateLayout(self):
#        """Layout of the windows in the frame"""
#        lBar, rBar = self.CreateBar()
#        self.address_list = AddressList(self, ["Name", "Email"], None)
#        self.address_book = AddressBook(self, self.ddata, self.address_list)
#        psizer = wx.BoxSizer(wx.HORIZONTAL)
#        rsizer = wx.BoxSizer(wx.VERTICAL)
#        lsizer = wx.BoxSizer(wx.VERTICAL)
#        rsizer.Add(rBar)
#        rsizer.Add(self.address_list, 1,  flag = wx.EXPAND)
#        lsizer.Add(lBar)
#        lsizer.Add(self.address_book, 1, flag = wx.EXPAND)
#        psizer.Add(lsizer, 1, flag = wx.EXPAND)
#        psizer.Add(rsizer, 2, flag = wx.EXPAND)
#        self.SetSizer(psizer)
#        size = psizer.GetMinSize()
#        print self.size
#        if size[0] < self.size[0]:
#            size[0] = self.size[0]
#        if size[1] < self.size[1]:
#            size[1] = self.size[1]
#        self.SetSize(size)
#        
#    def CreateBar(self):
#        """Create a button bar to control the window"""
#        add = wx.Button(self, id = wx.ID_ADD, style = wx.BU_EXACTFIT)
#        delete = wx.Button(self, id = wx.ID_DELETE, style = wx.BU_EXACTFIT)
#        to = wx.Button(self, -1, "To:", style = wx.BU_EXACTFIT)
#        cc = wx.Button(self, -1, "Cc:", style = wx.BU_EXACTFIT)
#        bcc = wx.Button(self, -1, "Bcc:", style = wx.BU_EXACTFIT)
#        add2 = wx.Button(self, -1, "Add", style = wx.BU_EXACTFIT)
#        delete2 = wx.Button(self, -1, "Delete", style = wx.BU_EXACTFIT)
#        self.Bind(wx.EVT_BUTTON, self.OnAddAddress, add)
#        self.Bind(wx.EVT_BUTTON, self.OnDeleteAddress, delete)
#        self.Bind(wx.EVT_BUTTON, self.OnTo, to)
#        self.Bind(wx.EVT_BUTTON, self.OnCc, cc)
#        self.Bind(wx.EVT_BUTTON, self.OnBcc, bcc)
#        self.Bind(wx.EVT_BUTTON, self.OnAddBook, add2)
#        self.Bind(wx.EVT_BUTTON, self.OnDeleteBook, delete2)
#        rightBar = wx.GridBagSizer(hgap = 1, vgap = 1)
#        rightBar.Add(add, pos = (0, 0))
#        rightBar.Add(delete, pos = (0, 1))
#        rightBar.Add(to, pos = (0, 2))
#        rightBar.Add(cc, pos = (0, 3))
#        rightBar.Add(bcc, pos = (0, 4))
#        rightBar.Add((1, 6), pos = (0, 5))
#        rightBar.AddGrowableCol(5)
#        leftBar = wx.BoxSizer(wx.HORIZONTAL)
#        leftBar.Add(add2)
#        leftBar.Add(delete2)
#        return leftBar, rightBar
#    
#    def OnAddAddress(self, event):
#        self.address_list.AddAddress()
#    
#    def OnDeleteAddress(self, event):
#        self.address_list.DeleteAddress()
#    
#    def OnTo(self, event):
#        self.__AddToGui("to")
#    
#    def OnCc(self, event):
#        self.__AddToGui("cc")
#    
#    def OnBcc(self, event):
#        self.__AddToGui("bcc")
#        
#    def __AddToGui(self, text):
#        address = self.address_list.GetSelectionData()
#        sum = []
#        for a in address:
#            print a
#            if a["NAME"]:
#                sum.append("%s <%s>" % (a['NAME'], a["EMAIL"]))
#            else:
#                sum.append("%s" % (a["EMAIL"]))
#        data = " , ".join(sum)
#        d = self.parent.database_handler
#        d.AddEmailFromAddressBook(text, data)
#    
#    def OnAddBook(self, event):
#        """Add the relevant book to the the list ctrl"""
#        self.address_book.AddBook()
#    
#    def OnDeleteBook(self, event):
#        """Delete the relevant book from the list ctrl"""
#        self.address_book.DeleteBook()
#        
#    def SendToDatabase(self, action, cls, *obj, **kw):
#        """Let the database handler take control of the command"""
#        self.dbhandler.SentToDatabase(action, cls, *obj, **kw)
#
#def random_book():
#    import random
#    booknames = ["Book%d" % d for d in range(25)]
#    ddata = {}
#    for b in booknames:
#        t = random.randint(1, 5)
#        ddata[b] = [{"NAME" : "First%d Last%d" % (d, d), "EMAIL": "%s-email%d" % (b, d)} for d in range(t * 10)]
#    return ddata
#
#if __name__ == '__main__':
#    ddata = random_book()
#    app = wx.PySimpleApp()
#    frame = AddressFrame(None, ddata)
#    frame.Show()
#    app.MainLoop()
#        
